<template>
  <div>
    <h2>分片上传测试</h2>
    <!-- 使用v-model绑定文件输入 -->
<!--    <input type="file" v-model="selectedFile" />-->
    <input type="file" @change="handleFileChange" />
    <button @click="startUpload" :disabled="uploading">开始上传</button>
    <button @click="cancelUpload" :disabled="!fileId">取消上传</button>

    <div>上传进度：</div>
    <div class="progress-bar">
      <div class="progress" :style="{ width: progressBarWidth + '%' }"></div>
    </div>

    <div :class="['status', { error: isStatusError }]">{{ status }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileId: null,
      chunkSize: 5 * 1024 * 1024, // 每片 5MB
      uploading: false,
      selectedFile: null, // 使用v-model绑定文件输入
      status: '',
      uploadedChunks: 0,
      totalChunks: 0,
      progressBarWidth: 0,
      isStatusError: false,
    };
  },
  methods: {
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.selectedFile = file;
      }
    },
    setStatus(msg, isError = false) {
      this.status = msg;
      this.isStatusError = isError;
      console.log("[上传状态]", msg);
    },
    async request(url, data, method = "POST") {
      const formData = new FormData();
      for (let key in data) {
        formData.append(key, data[key]);
      }

      try {
        const res = await fetch(url, { method, body: formData });
        const text = await res.text();
        console.log('Response:', text);

        let json = JSON.parse(text);
        if (!res.ok) throw new Error(json.error || json.message || '未知错误');
        return json;
      } catch (e) {
        throw new Error(`请求失败: ${e.message}`);
      }
    },
    async startUpload() {
      if (!this.selectedFile) return this.setStatus("请先选择文件");

      if (this.uploading) return this.setStatus("正在上传中...");
      this.uploading = true;

      const BASE_URL = "/api/fileController"; // 修改基础URL

      try {
        this.setStatus("初始化上传...");
        const initRes = await this.request(`${BASE_URL}/init`, {
          filename: this.selectedFile.name,
          fileSize: this.selectedFile.size,
          totalChunks: Math.ceil(this.selectedFile.size / this.chunkSize),
        });
        this.fileId = initRes.fileId;
        this.setStatus(`已初始化，fileId: ${this.fileId}`);

        this.totalChunks = Math.ceil(this.selectedFile.size / this.chunkSize);
        this.uploadedChunks = 0;

        for (let i = 0; i < this.totalChunks; i++) {
          const start = i * this.chunkSize;
          const end = Math.min(start + this.chunkSize, this.selectedFile.size);
          const chunk = this.selectedFile.slice(start, end);

          const formData = new FormData();
          formData.append("fileId", this.fileId);
          formData.append("chunkNumber", i + 1);
          formData.append("chunk", chunk);

          try {
            const res = await fetch(`${BASE_URL}/chunk`, {
              method: "POST",
              body: formData,
            });

            if (res.ok) {
              this.uploadedChunks++;
            } else {
              const text = await res.text();
              this.setStatus(`分片 ${i+1} 失败: ${text}`, true);
            }
          } catch (err) {
            this.setStatus(`分片 ${i+1} 网络错误: ${err.message}`, true);
          }

          this.progressBarWidth = Math.round((this.uploadedChunks / this.totalChunks) * 100);
          this.setStatus(`上传中... ${this.uploadedChunks}/${this.totalChunks}`);
        }

        if (this.uploadedChunks === this.totalChunks) {
          this.setStatus("正在合并文件...");
          const completeRes = await this.request(`${BASE_URL}/complete`, { fileId: this.fileId });
          this.setStatus(`✅ 上传成功！文件名: ${completeRes.objectName}`);
        } else {
          this.setStatus(`❌ 上传不完整 (${this.uploadedChunks}/${this.totalChunks})，无法合并`, true);
        }

      } catch (err) {
        this.setStatus("❌ 上传失败: " + err.message, true);
      } finally {
        this.uploading = false;
      }
    },
    async cancelUpload() {
      if (!this.fileId) return this.setStatus("无上传任务");
      if (!confirm("确定要取消上传吗？")) return;

      try {
        await fetch(`${BASE_URL}/abort`, {
          method: "POST",
          body: new FormData().append("fileId", this.fileId),
        });
        this.setStatus("已取消上传");
      } catch (err) {
        this.setStatus("取消失败: " + err.message, true);
      }
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
body {
  font-family: Arial, sans-serif;
  max-width: 600px;
  margin: 50px auto;
  padding: 20px;
}
.progress-bar {
  width: 100%;
  background: #eee;
  height: 20px;
  border-radius: 10px;
  overflow: hidden;
  margin: 10px 0;
}
.progress {
  height: 100%;
  background: #4caf50;
  transition: width 0.3s;
}
button {
  padding: 10px 15px;
  margin: 5px;
  font-size: 14px;
}
.status {
  color: #d32f2f;
  margin: 10px 0;
}
.error {
  color: red;
}
</style>